package com.javademo.asposewordjava.utils.pdf;


import cn.hutool.system.OsInfo;
import cn.hutool.system.SystemUtil;
import com.aspose.words.*;
import com.aspose.words.net.System.Data.DataRow;
import com.aspose.words.net.System.Data.DataTable;
import lombok.SneakyThrows;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * @author yonghaoRen
 * @Description:
 */
public class AsposeUtil {


    /**
     * 加载license 用于破解 不生成水印
     *
     * @author yonghaoRen
     * @date 2022/12/5 13:51
     */
    @SneakyThrows
    public static void getLicense() {
        try (InputStream is = AsposeUtil.class.getClassLoader().getResourceAsStream("License.xml")) {
            License license = new License();
            license.setLicense(is);
        }
    }

    /**
     * word转pdf
     *
     * @param wordPath word文件保存的路径
     * @param pdfPath  转换后pdf文件保存的路径
     * @author yonghaoRen
     * @date 2020/12/25 13:51
     */
    @SneakyThrows
    public static void wordToPdf(String wordPath, String pdfPath) {
        getLicense();
        File file = new File(pdfPath);
        try (FileOutputStream os = new FileOutputStream(file)) {
            OsInfo osInfo = SystemUtil.getOsInfo();
            if(osInfo.isLinux()){
                //指定字体源
                FontSettings.getDefaultInstance().
                        setFontsFolder("/usr/share/fonts", true);
            }
            Document doc = new Document(wordPath);
            doc.save(os, SaveFormat.PDF);
        }
    }


    /**
     * word 转 pdf
     * @param pdfFileName
     * @param wordPath
     * @param response
     */
    public static void downloadPdfByWord(String pdfFileName, String wordPath, HttpServletResponse response) {
        try {
            pdfFileName = URLEncoder.encode(pdfFileName, "UTF-8");
            response.reset();
            response.setContentType("application/pdf;charset=UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename="+pdfFileName);
            getLicense();
            Document doc = new Document(wordPath);
            doc.save(response.getOutputStream(), SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            File temFile = new File(wordPath);
            temFile.delete();
        }
    }

    public static void main(String[] args) throws Exception {
        System.out.println("Hello, AsPose Word!");
    }
}